﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Computer_Manager.DTO;
using Computer_Manager.BUS;
using DevExpress.XtraGrid.Views.Grid;

namespace Computer_Manager.GUI
{
    public partial class frmAddOrder : DevExpress.XtraEditors.XtraForm
    {
        private int _id_user;

        public int id_user
        {
            get { return _id_user; }
            set { _id_user = value; }
        }
        int id_order = 0;
        DataTable orderlist = null ;
        DataTable obj_sp = null;
        DTO_customer dto_cus = null;
        BUS_customer bus_cus = new BUS_customer();

        DTO_product dto_pro = null;
        BUS_product bus_pro = new BUS_product();

        DTO_order dto_order = null;
        BUS_order bus_order = new BUS_order();

        DTO_order_detail dto_order_de = null;
        BUS_order_detail bus_order_de = new BUS_order_detail();

        public frmAddOrder()
        {
            InitializeComponent();
            
        }

        private void frmAddOrder_Load(object sender, EventArgs e)
        {
            f_load();
        }

        private void f_load()
        {

            var all_order = bus_order.GetAll();
            btnExportOrder.Enabled = false;
            int codes_id = 0;
            int count_order = all_order.Rows.Count;
            if (count_order>0)
            {
                codes_id = int.Parse(all_order.Rows[count_order-1]["id_order"].ToString())+1;
            }
            else
            {
                codes_id = 1;
            }
            string codes_order = string.Format("{0:0000#}", codes_id) + "/" + DateTime.Today.Year.ToString();

            txtSoHoaDon.Text = codes_order;

            if (bool.Parse(rdgTypeOrder.Properties.Items[rdgTypeOrder.SelectedIndex].Value.ToString()))
            {
                dto_cus = new DTO_customer();
                dto_cus.type = false;
                lueTenKH.Properties.DataSource = bus_cus.GetByType(dto_cus);
                lueTenKH.Properties.DisplayMember = "name_cus";
                lueTenKH.Properties.ValueMember = "id_cus";

                grLueAddress.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLueAddress.Properties.DisplayMember = "address";
                grLueAddress.Properties.ValueMember = "id_cus";

                grLueEmail.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLueEmail.Properties.DisplayMember = "email";
                grLueEmail.Properties.ValueMember = "id_cus";

                grLuePhone.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLuePhone.Properties.DisplayMember = "phone";
                grLuePhone.Properties.ValueMember = "id_cus";
            }
            else
            {
                dto_cus = new DTO_customer();
                dto_cus.type = true;
                lueTenKH.Properties.DataSource = bus_cus.GetByType(dto_cus);
                lueTenKH.Properties.DisplayMember = "name_cus";
                lueTenKH.Properties.ValueMember = "id_cus";

                grLueAddress.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLueAddress.Properties.DisplayMember = "address";
                grLueAddress.Properties.ValueMember = "id_cus";

                grLueEmail.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLueEmail.Properties.DisplayMember = "email";
                grLueEmail.Properties.ValueMember = "id_cus";

                grLuePhone.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLuePhone.Properties.DisplayMember = "phone";
                grLuePhone.Properties.ValueMember = "id_cus";
            }


            orderlist = new DataTable();
            orderlist.Columns.Add("id_detail");
            orderlist.Columns.Add("Ma_Hang");
            orderlist.Columns.Add("Ten_Hang");
            orderlist.Columns.Add("So_Luong");
            orderlist.Columns.Add("Gia");
            orderlist.Columns.Add("Thanh_Tien");

            

            

            obj_sp = bus_pro.GetAll();

            
            reItiemGridLueMa_SP.DataSource = obj_sp;
            reItiemGridLueMa_SP.DisplayMember = "codes_pro";
            reItiemGridLueMa_SP.ValueMember = "id_pro";


            reItemGridLueTen_SP.DataSource = obj_sp;
            reItemGridLueTen_SP.DisplayMember = "name_pro";
            reItemGridLueTen_SP.ValueMember = "id_pro";

            loaddata();
        }

        private void grvOrderList_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView list = sender as GridView;

            int id_pro = 0;
            if (list.GetRowCellValue(e.RowHandle, "Ma_Hang").ToString() == "" && list.GetRowCellValue(e.RowHandle, "Ten_Hang").ToString()=="")
            {
                list.DeleteRow(list.FocusedRowHandle);
                XtraMessageBox.Show("Mã sản phẩm và tên sản phẩm không được trống", "Thông tin", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (list.GetRowCellValue(e.RowHandle, "Ma_Hang").ToString() != "")
            {
                id_pro = int.Parse(list.GetRowCellValue(e.RowHandle, "Ma_Hang").ToString());
            }
            else
            {
                id_pro = int.Parse(list.GetRowCellValue(e.RowHandle, "Ten_Hang").ToString());
            }
            dto_pro = new DTO_product();
            dto_pro.id_pro = id_pro;
            var data_pro = bus_pro.GetByID(dto_pro);
            if (list.IsNewItemRow(e.RowHandle))
            {
                if (CheckCart(id_pro))
                {
                    list.SetRowCellValue(e.RowHandle, "Ma_Hang", data_pro.Rows[0]["id_pro"]);
                    list.SetRowCellValue(e.RowHandle, "Ten_Hang", data_pro.Rows[0]["id_pro"]);
                    list.SetRowCellValue(e.RowHandle, "Gia", data_pro.Rows[0]["price_out"]);
                    list.SetRowCellValue(e.RowHandle, "So_Luong", 1);
                    list.SetRowCellValue(e.RowHandle, "Thanh_Tien", float.Parse(data_pro.Rows[0]["price_out"].ToString()) * int.Parse(list.GetRowCellValue(e.RowHandle, "So_Luong").ToString()));
                }
                else
                {
                    list.DeleteRow(list.FocusedRowHandle);
                    XtraMessageBox.Show("Sản phẩm đã được thêm. Để thêm sản phẩm bạn có thể cập nhật lại số lượng.","Thông tin",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    loaddata();
                }

            }
            else
            {
                if (CheckCartU(id_pro))
                {
                    list.SetRowCellValue(e.RowHandle, "Ma_Hang", data_pro.Rows[0]["id_pro"]);
                    list.SetRowCellValue(e.RowHandle, "Ten_Hang", data_pro.Rows[0]["id_pro"]);
                    list.SetRowCellValue(e.RowHandle, "Gia", data_pro.Rows[0]["price_out"]);
                    //list.SetRowCellValue(e.RowHandle, "So_Luong", list.GetRowCellValue(e.RowHandle,"So_Luong"));
                    list.SetRowCellValue(e.RowHandle, "Thanh_Tien", float.Parse(data_pro.Rows[0]["price_out"].ToString()) * int.Parse(list.GetRowCellValue(e.RowHandle, "So_Luong").ToString()));

                }
                else
                {
                    list.DeleteRow(list.FocusedRowHandle);
                    XtraMessageBox.Show("Sản phẩm đã được thêm. Để thêm sản phẩm bạn có thể cập nhật lại số lượng.", "Thông tin", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    loaddata();
                }
                
            }
            

        }
        private void loaddata()
        {
            grcOrderList.DataSource = orderlist;
            lblTongTien.Text = getAllMoney().ToString();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            loaddata();
        }
        public bool CheckCart(int Pid)
        {
           
            for (int i = 0; i < orderlist.Rows.Count; i++)
            {
                if (int.Parse(orderlist.Rows[i]["Ma_Hang"].ToString()) == Pid)
                {
                    return false;
                }
            }
            return true;
        }
        public bool CheckCartU(int Pid)
        {
            int j = 0;
            for (int i = 0; i < orderlist.Rows.Count; i++)
            {
                if (int.Parse(orderlist.Rows[i]["Ma_Hang"].ToString()) == Pid)
                {
                    j++;
                    if (j>=2)
                    {
                        return false;
                    }
                    
                }
            }
            return true;
        }
        private float getAllMoney()
        {
            float Money = 0;
            for (int i = 0; i < orderlist.Rows.Count; i++)
            {
                try
                {
                    Money += float.Parse(orderlist.Rows[i]["Thanh_Tien"].ToString());
                }
                catch (Exception) { }
            }
            return Money;
        }

        private void grvOrderList_Click(object sender, EventArgs e)
        {
            loaddata();
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            frmAddOrder_Load(sender, e);
            btnSave.Enabled = true;
        }

        private void rdgTypeOrder_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bool.Parse(rdgTypeOrder.Properties.Items[rdgTypeOrder.SelectedIndex].Value.ToString()))
            {
                dto_cus = new DTO_customer();
                dto_cus.type = false;
                lueTenKH.Properties.DataSource = bus_cus.GetByType(dto_cus);
                lueTenKH.Properties.DisplayMember = "name_cus";
                lueTenKH.Properties.ValueMember = "id_cus";

                grLueAddress.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLueAddress.Properties.DisplayMember = "address";
                grLueAddress.Properties.ValueMember = "id_cus";

                grLueEmail.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLueEmail.Properties.DisplayMember = "email";
                grLueEmail.Properties.ValueMember = "id_cus";

                grLuePhone.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLuePhone.Properties.DisplayMember = "phone";
                grLuePhone.Properties.ValueMember = "id_cus";
            }
            else
            {
                dto_cus = new DTO_customer();
                dto_cus.type = true;
                lueTenKH.Properties.DataSource = bus_cus.GetByType(dto_cus);
                lueTenKH.Properties.DisplayMember = "name_cus";
                lueTenKH.Properties.ValueMember = "id_cus";

                grLueAddress.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLueAddress.Properties.DisplayMember = "address";
                grLueAddress.Properties.ValueMember = "id_cus";

                grLueEmail.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLueEmail.Properties.DisplayMember = "email";
                grLueEmail.Properties.ValueMember = "id_cus";

                grLuePhone.Properties.DataSource = bus_cus.GetByType(dto_cus);
                grLuePhone.Properties.DisplayMember = "phone";
                grLuePhone.Properties.ValueMember = "id_cus";
            }

        }

        private void lueTenKH_EditValueChanged(object sender, EventArgs e)
        {
            grLueAddress.EditValue = lueTenKH.EditValue;
            grLuePhone.EditValue = lueTenKH.EditValue;
            grLueEmail.EditValue = lueTenKH.EditValue;
        }

        private void grLuePhone_EditValueChanged(object sender, EventArgs e)
        {
            grLueAddress.EditValue = grLuePhone.EditValue;
            lueTenKH.EditValue = grLuePhone.EditValue;
            grLueEmail.EditValue = grLuePhone.EditValue;
        }

        private void grLueAddress_EditValueChanged(object sender, EventArgs e)
        {
            grLuePhone.EditValue = grLueAddress.EditValue;
            lueTenKH.EditValue = grLueAddress.EditValue;
            grLueEmail.EditValue = grLueAddress.EditValue;
        }

        private void grLueEmail_EditValueChanged(object sender, EventArgs e)
        {
            grLuePhone.EditValue = grLueEmail.EditValue;
            lueTenKH.EditValue = grLueEmail.EditValue;
            grLueAddress.EditValue = grLueEmail.EditValue;
        }
        

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (lueTenKH.EditValue.ToString() == "")
            {
                XtraMessageBox.Show("Bạn chưa nhập thông tin khách hàng","Thông tin",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                return;
            }
            if (orderlist.Rows.Count<1)
            {
                XtraMessageBox.Show("Bạn chưa chọn sản phẩm nào. Vui lòng chọn ít nhất 1 sản phẩm", "Thông tin", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            dto_order = new DTO_order();
            dto_order.id_cus = int.Parse(lueTenKH.EditValue.ToString());
            dto_order.codes_order = txtSoHoaDon.Text;
            dto_order.id_user = _id_user;
            dto_order.date_create = DateTime.Now;
            dto_order.total_money = getAllMoney();
            dto_order.status = false;
            id_order = bus_order.order_insert(dto_order);
            //XtraMessageBox.Show(id_order.ToString(), "Thông tin", MessageBoxButtons.OK, MessageBoxIcon.Information);
            for (int i = 0; i < orderlist.Rows.Count; i++)
            {
                dto_order_de = new DTO_order_detail();
                dto_order_de.id_order = id_order;
                dto_order_de.id_product = int.Parse(orderlist.Rows[i]["Ma_Hang"].ToString());
                dto_order_de.amount = int.Parse(orderlist.Rows[i]["So_Luong"].ToString());
                orderlist.Rows[i]["id_detail"] = bus_order_de.order_detail_insert(dto_order_de);
            }
            //if (bus_order.order_insert(dto_order))
            //{
            //    XtraMessageBox.Show("Lưu thông tin hóa đơn thành công", "Thông tin", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
            XtraMessageBox.Show("Lưu thông tin hóa đơn thành công", "Thông tin", MessageBoxButtons.OK, MessageBoxIcon.Information);
            btnSave.Enabled = false;
            btnExportOrder.Enabled = true;
            
        }

        private void btnExportOrder_Click(object sender, EventArgs e)
        {
            //grvOrderList.ShowPrintPreview();
            //DataSet dsOrder = new DataSet();
            //dsOrder.Tables.Add(data_order);
            DataSet dsOrder = new DataSet();
            DataTable dtBill = new DataTable();
            dtBill.Columns.Add("Ma_Hang", typeof(string));
            dtBill.Columns.Add("Ten_Hang", typeof(string));
            dtBill.Columns.Add("Gia", typeof(string));
            dtBill.Columns.Add("So_Luong", typeof(string));
            dtBill.Columns.Add("Thanh_Tien", typeof(string));

            //DataView dv = (DataView)(gvBill.DataSource);
            //dtBill = dv.ToTable();
            DataRow dr;
            for (int i = 0; i < grvOrderList.RowCount; i++)
            {
                dr = dtBill.NewRow();
                dr = (DataRow)grvOrderList.GetDataRow(i);
                dtBill.ImportRow(dr);
            }
            dsOrder.Tables.Add(dtBill);

            XtraReportOrder rptOrder = new XtraReportOrder();

            rptOrder.DataSource = dsOrder;
            rptOrder.DataMember = dsOrder.Tables[0].TableName;

            rptOrder.lblFullName.Text = lueTenKH.Text;
            rptOrder.lblCodesOrder.Text = txtSoHoaDon.Text;
            rptOrder.lblAddress.Text = grLueAddress.Text;
            rptOrder.lblEmail.Text = grLueEmail.Text;
            rptOrder.lblPhone.Text = grLuePhone.Text;
            rptOrder.lblPrintDate.Text = DateTime.Now.ToString();
            rptOrder.lblCodesPro.DataBindings.Add("Text", null, "Ma_Hang");
            rptOrder.lblNamePro.DataBindings.Add("Text", null, "Ten_Hang");
            rptOrder.lblPrice.DataBindings.Add("Text", null, "Gia");
            rptOrder.lblAmount.DataBindings.Add("Text", null, "So_Luong");
            rptOrder.lblMoney.DataBindings.Add("Text", null, "Thanh_Tien");
            rptOrder.PrintDialog();
        }



       
    }
}